package saleMarket.service;

import saleMarket.dao.CommunicationDao;
import saleMarket.domain.Communication;
import util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;

/**
 * @author 徐元坤 付饶
 * @version 1.0  12-12-2020
 */

public class CommunicationService {
    private static CommunicationDao communicationDao = CommunicationDao.getInstance();
    private static CommunicationService communicationService=new CommunicationService();
    private CommunicationService(){}
    public static CommunicationService getInstance(){return communicationService;}

    public Collection<Communication> startAndRefresh(int customer_id, int shopOwner_id) throws SQLException{
        Connection conn = JdbcHelper.getConn();
        conn.setAutoCommit(false);
        Collection<Communication> answer = null;
        try {
            answer = communicationDao.find(customer_id,shopOwner_id,conn);
            conn.commit();
        }catch (SQLException e){
            conn.rollback();
        }finally {
            conn.setAutoCommit(true);
            JdbcHelper.close(conn);
        }
        return answer;
    }

    public Collection<Communication> communicate(Communication communication) throws SQLException{
        Connection conn = JdbcHelper.getConn();
        conn.setAutoCommit(false);
        Collection<Communication> answer = null;
        try {
            communicationDao.add(communication,conn);
            answer = communicationDao.find(communication.getCustomer().getId()
                    ,communication.getShopOwner().getId(),conn);
            conn.commit();
        }catch (SQLException e){
            conn.rollback();
        }finally {
            conn.setAutoCommit(true);
            JdbcHelper.close(conn);
        }
        return answer;
    }

    public boolean deleteCase(int customer_id, int shopOwner_id) throws SQLException{
        Connection conn = JdbcHelper.getConn();
        conn.setAutoCommit(false);
        boolean deleted = false;
        try {
            deleted = communicationDao.delete(customer_id,shopOwner_id,conn);
            conn.commit();
        }catch (SQLException e){
            conn.rollback();
        }finally {
            conn.setAutoCommit(true);
            JdbcHelper.close(conn);
        }
        return deleted;
    }

}
